package com.zhimo.restrictionmanager;

import java.util.ArrayList;
import java.util.List;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Process;
import android.os.RemoteException;
import android.os.UserManager;
import android.util.Log;

import com.zhimo.restrictionmanager.aidl.IRestrictionManager;

public class RestrictionManagerService extends Service {
	private static final String TAG = "RestrictionManager";
	private static final boolean TEST_MODE = true;
			
	private RestrictionManagerStub mStub;
	private List<User> mUserlist = new ArrayList<User>();;
	private UserManager mUserManager;
	
	@Override
	public void onCreate(){
		mUserManager = (UserManager)getSystemService(Context.USER_SERVICE);
		getAllUserRestrictions();
	}	

	@Override
	public void onDestroy(){
		
	}	
	
	@Override
	public IBinder onBind(Intent intent) {
		if(mStub == null)
		{			
			mStub = new RestrictionManagerStub(this);
		}
		
		return mStub;
	}	
	

	private void getAllUserRestrictions()
	{
		//dummy
		{
			mUserlist.add(new User(0));
		}
	}

	private class User
	{
		private int mId;
		private List<Package> mWhiteList = new ArrayList<Package>();	
		
		public User(int userId)
		{
			mId = userId;
			readWhitelist();
		}
		
		public int getUserId()
		{
			return mId;
		}
		
		public boolean isInWhitelist(String PackageName)
		{
			Log.d(TAG,"isInWhitelist: PackageName ="+PackageName);
			if(PackageName != null)
			{
				for(Package whitepkg: mWhiteList)
				{
					if(whitepkg.getName().equals(PackageName))
					{
						return true;
					}
				}
			}
			
			return false;
		}
		
		private void readWhitelist()
		{
			//dummy
			{	
				mWhiteList.add(new Package("com.example.test"));
			}
		}		
		
	}	
	
	private class Package
	{
		private String mName;
		
		public Package(String packageName)
		{
			mName = packageName;
		}
		
		public String getName()
		{
			return mName;
		}
	}
	

	private class RestrictionManagerStub extends IRestrictionManager.Stub{
		private Context mContext;
		
		public RestrictionManagerStub(Context context) {
			mContext = context;
		}

		@Override
		public boolean isRestrictedPackage(String packageName, int userId)
				throws RemoteException {
			if(!TEST_MODE)
			{
				if(Binder.getCallingUid()!= Process.SYSTEM_UID)
				{
					Log.e(TAG,"Only system user can call isRestrictedPackage");
					throw new SecurityException();
				}				
			}
			
			for(User i: mUserlist)
			{
				if(i.getUserId() == userId)
				{
					return (!i.isInWhitelist(packageName));
				}
			}

			return true;
		}
		
	}

}